#include "System.h"

static uint16_t LedBlinkTicker;
static uint16_t LedBlinkRate;

volatile uint32_t  StartupDelay;

void SetLED_BlinkRate(uint16_t BR)
{
	LedBlinkRate = BR;
}

void SysTick_Handler()
{
	if(StartupDelay>0)
		StartupDelay--;

	if(LedBlinkRate == LED_ALWAYS_OFF)
	{
		LED_OFF;
	}
	else if(LedBlinkRate == LED_ALWAYS_ON)
	{
		LED_ON;
	}
	else
	{
		LedBlinkTicker++;
		if(LedBlinkTicker>=LedBlinkRate)
		{
			LED_TOGGLE;
			LedBlinkTicker = 0;
		}

	}
}

USB_DEV_INFO DeviceInfo;
MSC_DEVICE_INFO MscDevInfo;
ROM ** rom = (ROM **)0x1fff1ff8;

#define     EN_TIMER32_1    (1<<10)
#define     EN_IOCON        (1<<16)
#define     EN_USBREG       (1<<14)

void InitUSB_MSC()
{
	int n;

	MscDevInfo.idVendor = USB_VENDOR_ID;
	MscDevInfo.idProduct = USB_PROD_ID;
	MscDevInfo.bcdDevice = USB_DEVICE;
	MscDevInfo.StrDescPtr = (uint32_t)&USB_StringDescriptor[0];
	MscDevInfo.MSCInquiryStr = (uint32_t)&InquiryStr[0];
	MscDevInfo.BlockSize =512;
	MscDevInfo.BlockCount = 4096;
	MscDevInfo.MemorySize = 2097152;
	MscDevInfo.MSC_Read = MSC_MemoryRead;
	MscDevInfo.MSC_Write = MSC_MemoryWrite;

	DeviceInfo.DevType = USB_DEVICE_CLASS_STORAGE;
	DeviceInfo.DevDetailPtr = (uint32_t)&MscDevInfo;

	/* Enable Timer32_1, IOCON, and USBREG blocks */
	LPC_SYSCON->SYSAHBCLKCTRL |= (EN_TIMER32_1 | EN_IOCON | EN_USBREG);

	(*rom)->pUSBD->init_clk_pins();   /* Use pll and pin init function in rom */

	/* insert a delay between clk init and usb init */
	for (n = 0; n < 75; n++) {
	}

	(*rom)->pUSBD->init(&DeviceInfo);  /* USB Initialization */
	init_msdstate();					 /* Initialize Storage state machine */
	(*rom)->pUSBD->connect(TRUE);      /* USB Connect */

}

void USB_IRQHandler(void)
{
(*rom)->pUSBD->isr();
}

